package com.example.demo.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

public class HttpUtil {

	private static final CookieStore COOKIE_STORE = new BasicCookieStore();
	private static final RequestConfig GLOBAL_CONFIG = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD)
			.build();

	/**
	 * 创建支持SSL的HttpClient
	 *
	 * @return CloseableHttpClient
	 * @throws NoSuchAlgorithmException
	 * @throws KeyStoreException
	 * @throws KeyManagementException
	 */
	private static CloseableHttpClient createHttpClient()
			throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
		SSLContext sslContext = SSLContextBuilder.create()
				.loadTrustMaterial((chain, authType) -> true) // 信任所有证书
				.build();

		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

		return HttpClients.custom()
				.setDefaultRequestConfig(GLOBAL_CONFIG)
				.setDefaultCookieStore(COOKIE_STORE)
				.setSSLSocketFactory(sslsf)
				.build();
	}

	/**
	 * 发送HttpGet请求并返回响应内容
	 *
	 * @param address 请求的URL地址
	 * @return 响应内容
	 */
	public static byte[] sendGetRequest(String address) {
		try (CloseableHttpClient httpClient = createHttpClient()) {
			HttpGet httpGet = new HttpGet(address);
			try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
				int statusCode = response.getStatusLine().getStatusCode();
				System.out.println("Status line: " + statusCode + ", " + response.getStatusLine().getReasonPhrase());

				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String contentType = entity.getContentType() != null ? entity.getContentType().getValue() : "";
					if (contentType.contains("charset=")) {
						System.out.println("HTTP响应头 Content-Type 包含 charset 参数: " + contentType);
					} else {
						System.out.println("HTTP响应头 Content-Type 不包含 charset 参数: " + contentType);
					}
					// String content = getContentAsString(entity);
					byte[] content = EntityUtils.toByteArray(entity);
					// System.out.println("Page: " + content);
					return content;
				}
			}
		} catch (Exception e) {
			System.err.println("Error executing HTTP GET request: " + e.getMessage());
		}
		return null;
	}

	/**
	 * 发送HttpPost请求并返回响应内容
	 *
	 * @param address 请求的URL地址
	 * @param body    请求体内容
	 * @return 响应内容
	 */
	public static String sendPostRequest(String address, String body) {
		try (CloseableHttpClient httpClient = createHttpClient()) {
			HttpPost httpPost = new HttpPost(address);
			httpPost.setEntity(new StringEntity(body));

			try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
				int statusCode = response.getStatusLine().getStatusCode();
				System.out.println("Status line: " + statusCode + ", " + response.getStatusLine().getReasonPhrase());

				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String content = getContentAsString(entity);
					System.out.println("Response: " + content);
					return content;
				}
			}
		} catch (Exception e) {
			System.err.println("Error executing HTTP POST request: " + e.getMessage());
		}
		return null;
	}

	/**
	 * 将响应内容转换为字符串，并处理编码
	 *
	 * @param entity 响应实体
	 * @return 响应内容字符串
	 * @throws IOException
	 */
	private static String getContentAsString(HttpEntity entity) throws IOException {
		ContentType contentType = ContentType.getOrDefault(entity);
		Charset charset = contentType.getCharset() != null ? 
			contentType.getCharset() : StandardCharsets.ISO_8859_1;
		return EntityUtils.toString(entity, charset);
	}

	/**
	 * 将响应内容保存到文件
	 *
	 * @param address 请求的URL地址
	 * @param content 响应内容
	 */
	public static void saveContentToFile(String address, String content) {
		try {
			URL url = new URL(address);
			Path filePath = Paths.get(url.getHost() + ".txt");
			Files.write(filePath, content.getBytes(StandardCharsets.UTF_8)); // 使用UTF-8编码保存文件
			System.out.println("Content saved to file: " + filePath.toAbsolutePath());
		} catch (IOException e) {
			System.err.println("Error saving content to file: " + e.getMessage());
		}
	}

	public static void main(String[] args) {
		String address = "https://example.com";
		String postBody = "{\"key\": \"value\"}";

		// 发送GET请求
		byte[] getResponseBytes = sendGetRequest(address);
		

		// 发送POST请求
		String postResponse = sendPostRequest(address, postBody);
		if (postResponse != null) {
			saveContentToFile(address, postResponse);
		}
	}
}
